// src/directives/highlight.js

const highlight = {
  bind(el, binding) {
    setHighlight(el, binding.value);
  },
  update(el, binding) {
    setHighlight(el, binding.value);
  },
};

function setHighlight(el, value) {
  // 解析参数
  let keyword = '';
  let color = '#000'; // 默认文字色
  let backgroundColor = '#ffdd00'; // 默认黄底

  // 如果参数是字符串，直接使用
  if (typeof value === 'string') {
    keyword = value;
  } else if (value && typeof value === 'object') {
    keyword = value.keyword || '';
    color = value.color || '#000';
    backgroundColor = value.backgroundColor || '#ffdd00';
  }

  // 清理空格
  keyword = keyword.trim();

  if (!keyword) {
    // 关键词为空 → 恢复原始文本
    el.innerHTML = el.innerText;
    return;
  }

  const text = el.innerText;

  // 转义正则特殊字符
  const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const regex = new RegExp(`(${escapedKeyword})`, 'gi');

  // 使用内联样式，避免依赖 CSS 类名
  const styleStr = `color: ${color}; background-color: ${backgroundColor}; 
                    border-radius: 2px; padding: 0 2px; font-weight: bold;`;

  const highlightedText = text.replace(
    regex,
    `<span style="${styleStr}">$1</span>`
  );

  el.innerHTML = highlightedText;
}

export default highlight;
